let reDownload = false;

function handleDownloadRequest(downloadItem) {
    if (reDownload) {
        reDownload = false;
        return;
    }

    chrome.downloads.cancel(downloadItem.id, () => {
        if (
            !chrome.runtime.lastError &&
            downloadItem.finalUrl
        ) {
            const downloadUrl = encodeURIComponent(downloadItem.finalUrl)
            fetch(`http://127.0.0.1:19527/download/${downloadUrl}`).then(res => {
            }).catch((err) => {
                reDownload = true;
                chrome.storage.local.set({ reDownload: true });

                chrome.downloads.download({ url: downloadItem.finalUrl }, (newDownloadId) => {
                    if (chrome.runtime.lastError) {
                        console.error(
                            'Failed to re-add download:',
                            chrome.runtime.lastError.message
                        );
                    } else {
                        console.log('Download re-added to browser:', newDownloadId);
                    }
                });
            });
        }
    })
}

setTimeout(() => {
    chrome.downloads.onCreated.addListener(handleDownloadRequest)

    chrome.downloads.onChanged.addListener(function (delta) {
        if (delta.state && delta.state.current === 'complete') {
            console.log('Download completed: ', delta)
        }
    })
}, 1000)

